package corp.sunny.sso.auth;

import javax.security.auth.login.LoginException;

import org.apache.log4j.Logger;

import corp.sunny.commons.util.security.JAASLoginModule;
import corp.sunny.commons.util.security.JAASPrincipal;
import corp.sunny.commons.util.spring.SpringUtil;
import corp.sunny.frameworks.dao.BaseDAO;
import corp.sunny.sso.dao.AuthenticationServiceDAO;
import corp.sunny.sso.domain.SSOUserAcct;

/**
 * @File: SSOModule.java
 * 
 * @Date: Jun 9, 2011
 * @Author: Subhash Bavi
 * @Description: Custom implementation of JAAS Login Module
 * @Copyright Sunny Corporation - 2011
 */
public class SSOLoginModule extends JAASLoginModule {

	final Logger LOG = Logger.getLogger(SSOLoginModule.class);

	private String user;
	private String passwd;

	private SSOUserAcct ssoUserAccount = (SSOUserAcct) SpringUtil
			.getBean("ssoUserAcct");
	private SSOUserAcct iAccount = (SSOUserAcct) SpringUtil
			.getBean("ssoUserAcct");

	private BaseDAO dao = new AuthenticationServiceDAO();

	/*
	 * Login: JAAS lifecycle method
	 * 
	 * (non-Javadoc)
	 * 
	 * @see javax.security.auth.spi.LoginModule#login()
	 */
	public boolean login() throws LoginException {

		try {
			// Retrieve the username and password from JAASPrincipal
			JAASPrincipal jaasPrincipal = (JAASPrincipal) super.subject
					.getPrincipals().iterator().next();

			user = jaasPrincipal.getName();
			passwd = (String) jaasPrincipal.getJAASPrincipal();
			ssoUserAccount.setUser(user);
			ssoUserAccount.setPasswd(passwd);

			// Call DAO
			iAccount = (SSOUserAcct) dao.find(ssoUserAccount);
		} catch (Exception e) {
			LOG.error("Unknown exception occured while loginContext.login()", e);
			throw new LoginException(
					"Error: Unknown exception occured while loginContext.login()");
		}
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.security.auth.spi.LoginModule#commit()
	 */
	public boolean commit() throws LoginException {
		super.commit(iAccount.getUser(), iAccount);

		// Clear the credential's
		this.user = this.passwd = null;
		return true;
	}
}
